﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            //SetVal();
            
            var task = Task.Factory.StartNew(SetVal);
            sw.Stop();

            label1.Text = "执行完毕，" + sw.ElapsedMilliseconds + "毫秒";
        }

        public void Set(int val)
        {
            if (listBox1.InvokeRequired)
            {
                Action<int> action = Set;

                this.Invoke(action, val);
            }
            else
            {
                listBox1.Items.Insert(0, "val=" + val);
            }
        }

        public void SetVal()
        {
            int number = int.Parse(textBox1.Text);

            for (int i = 0; i < number; i++)
            {
                Set(i);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
           /* Task.Run(() =>
            {
                Thread.Sleep(2000);
                Action showMessage = () => listBox1.Items.Insert(0, "val=" + val); ;
                listBox1.Invoke(showMessage);
            });*/
        }

        private void button2_Click_1(object sender, EventArgs e)
        {

        }
    }
}
